<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
defined ('IN_AGORA') or die;

class TaskController extends AgoraController {
	
	function __construct() {
		parent::__construct();
		$this->loadDefaultView();

        JPluginHelper::importPlugin( 'agora', 'agoraautoarticle');
		$dispatcher =& JDispatcher::getInstance();
        $params=array();
        $dispatcher->trigger( 'onExportAllForumsArticles', $params);
	}

	function _topicView() {
	
		$cat_id = Agora::getVar('id',null);
		$cat_id = !(int)$cat_id ? 0 : (int)$cat_id;
		$viewtype = Agora::getSessionVar('view','');
		
		$topic_model = & Model::getInstance('TopicModel');

		if ($this->agora_user['is_superadmin']) {
			$allowed_forums = null;
		} else {
			$allowed_forums = $this->access_model->getAllowedForums($this->agora_user['id']);
		}
		
		$sort_dir = Agora::getVar('filter_order_Dir','DESC');
		$sort_field = Agora::getVar('filter_order');
		
		// sanity checks
		if (strcasecmp($sort_dir,'asc') != 0 && strcasecmp($sort_dir,'desc')) {
			$sort_dir = 'asc';
		}

		if (!in_array($sort_field,array('id','num_replies','last_post'))) {
			$sort_field = null;
		}
		
		//Joopport modified

		$topic_count = ($viewtype == 'topic' && (int)$cat_id) 
						? $topic_model->loadAllCountByCat($cat_id, $allowed_forums) - 1 
						: $topic_model->loadAllCount($allowed_forums);
		
		//END of joopport
		
		$per_page = intval($this->agora_user['disp_topics']) > 0 ? $this->agora_user['disp_topics'] : intval($this->agora_config['o_disp_topics_default']);
		$page_num = ceil(((int)$topic_count + 1) / $per_page);
		$this->setPagination($page_num);

		$pathway = $this->helper('pathway');
		$pathname = ($viewtype == 'topic' && (int)$cat_id) ? $this->forumList[$cat_id]['cat_name'] : Agora::lang('All topics');
		$pathway->add($pathname,'');
		
		if (!$sort_field)
		$topic_model->setOrder('ORDER BY last_post DESC');
		else 
		$topic_model->setOrder("ORDER BY $sort_field $sort_dir");
		
		//joopport modified
		$topics = ($viewtype == 'topic' && (int)$cat_id) 
				? $topic_model->loadAllByCat($cat_id, '',  $per_page, Agora::getPage($page_num), $allowed_forums) 
				: $topic_model->loadAll('', $per_page, Agora::getPage($page_num), $allowed_forums);
		
		//END of joopport

		// we get forum names from forumList - to not make additional queries or break models
		$forums = array();
		foreach ($this->forumList as $cat) {
			foreach ($cat['forums'] as $forum) {
				$forums[$forum['id']] = $forum['forum_name'];
			}
		}

		// don't do this in prepareTopic - later we will use helper instead of prepareTopic - it's redundant in this controller
		foreach ($topics as $id=>$topic) {
			if (!isset($forums[$topic['forum_id']])) {
				unset($topics[$id]);
			}
		}

		$topic_helper = & $this->helper('topic');
		$topics = $topic_helper->processRatings($topics);
		$topics = $topic_helper->processTopics($topics);

//		$topics = $this->_prepareTopics($topics);
		$this->view->assign('star_path',Agora::getRoot()."img/rate_stars/default_stars/");
		$this->view->assignRef('topics',$topics);
	}

	function _forumView()
	{
		$cat_id = Agora::getVar('id',null);
		$cat_id = !(int)$cat_id ? 0 : (int)$cat_id;
		$cat_list = null;

		if (!(int)$cat_id) {
			$cat_list = $this->forumList;
		} else {
			$catnav_helper = & $this->helper('catnav');
			$catnav_helper->fromCategory($cat_id);
			$current_category = $this->forumList[$cat_id]['cat_name'];

			$pathway = & $this->helper('pathway');
			$pathway->push($current_category,Agora::makeURL(array('id' => $cat_id)));
			
			$cat_list = array($cat_id => $this->forumList[$cat_id]);
		}

		if (!$this->agora_user['is_guest'] && $this->agora_user['disp_posts'] > 0) {
			$per_page = intval($this->agora_user['disp_posts']);
		} else {
			$per_page = intval($this->agora_config['o_disp_posts_default']);
		}

		// array of top-level forum ids
		$ids = array();
		
		// We just rebuild $this->forumList to avoid more queries
		foreach ($cat_list as $id=>$cat) {
			$cat_list[$id]['id'] = $cat['cat_id'];
			if (count($cat['forums']))
			foreach ($cat['forums'] as $forum_id => $forum) {
				// prevent XSS in tooltip
				$cat_list[$id]['forums'][$forum_id]['postcontent'] = Agora::escape($cat_list[$id]['forums'][$forum_id]['postcontent']);
				if ($forum['level'] > 1) {
					unset($cat_list[$id]['forums'][$forum_id]);
					continue;
				}

				if ($forum['level'] == 0) {
					$ids[] = $forum['id'];
					$parent = & $cat_list[$id]['forums'][$forum_id];
					$parent['subforums'] = array();
					continue;
				}

				if ($forum['level'] == 1 && isset($parent)) {
					$parent['subforums'][] = $forum;
					unset($cat_list[$id]['forums'][$forum_id]);
				}
			}
		}
		
		$forum_model = & Model::getInstance('ForumModel');

		// collect latest posts for top-level forums
		$posts = array();
		if (count($cat_list))
		foreach ($cat_list as $cat) {
			if (count($cat['forums']))
			foreach ($cat['forums'] as $forum) {
				if ($forum['last_post_id']) {
					$posts[] = $forum['last_post_id'];
				}
			}
		}

		$topic_model = & Model::getInstance('TopicModel');
		$subjects = $topic_model->loadSubjectsMess($posts);

		$topics = array();
		foreach ($subjects as $subject) {
			$topics[] = $subject['topic_id'];
		}

		$unread = $topic_model->filterRead($topics, $this->agora_user['id']);

		$read_timeout = AGORA_TIME - intval($this->agora_config['o_timeout_visit']) * 86400;
		
		foreach ($subjects as $subject) {
			$cat_id = $subject['cat_id'];

			$forum_id = $subject['forum_id'];

			// forum from subject may be one of subforums
			// we go to top-level forum here. A little hard to read, but should be php4 compatible
			
			if (array_key_exists($forum_id, $this->forumList[$cat_id]['forums'])) {
				while ($this->forumList[$cat_id]['forums'][$forum_id]['parent_forum_id'] && isset($this->forumList[$cat_id]['forums'][$this->forumList[$cat_id]['forums'][$forum_id]['parent_forum_id']])) {
					$forum_id = $this->forumList[$cat_id]['forums'][$forum_id]['parent_forum_id'];
				}
			}
			
			$num_pages = ceil(($subject['num_replies'] + 1) / $per_page);

			/*foreach ($cat_list as $cat) {
				if ($cat['id'] == $cat_id) {
					$category = & $cat;
					break;
				}
			}*/
			
			// will stay like this for now as it causes problems with big non-latin posts
			/*
			$mess_text = $subject['message'];
			
			$mess_text = preg_replace('#\[quote(.*?)\[/quote\]#si', '', $mess_text);
			$mess_text = preg_replace('|[[\/\!]*?[^\[\]]*?]|si', '', $mess_text);
			$mess_text = strip_tags($mess_text);
			
			$length = strlen($mess_text);
			
			if ($length > 90) {
				$mess_text = JString::substr($mess_text, 0, 90).'...';
			}
			
			$subject['message'] = $mess_text;
			*/
			
			if (!isset($cat_list[$cat_id])) continue;
			$category = & $cat_list[$cat_id];

			$forum = & $category['forums'][$forum_id];
			
			/*			
			while ($forum['parent_forum_id'] && isset($category['forums'][$forum['parent_forum_id']])) {
				$forum = & $category['forums'][$forum['parent_forum_id']];
			}*/
			
			//$forum = & $category['forums'][$forum_id];

			/*
			if (count($forum['subforums']) > 0) {
				list($num_topics,$num_posts) = $forum_model->loadSubforumsCounters($forum_id);
				$forum['num_topics'] += $num_topics;
				$forum['num_posts'] += $num_posts;
			}*/

			$forum['subject'] = $subject['subject'];

			$topic_id = $subject['topic_id'];
			$forum['last_post_topic_id'] = $topic_id;
			$forum['num_pages'] = $num_pages;
			$forum['title'] = $subject['message'];


			$status = '';
			if ($this->agora_user['id'] && in_array($topic_id,$unread) && $forum['last_post'] > $read_timeout) {
				$status = 'new';
			}

            if ($subject['sticky']) $status .= 'sticky';
            if ($subject['closed']) $status .= 'closed';
            if ($subject['num_replies'] >= 19) $status .= 'hot';

			if (!$status) {
				$status = 'icon';
			}

			$forum['status'] = $status;

		}

		/*
		unset($category);
		
		foreach ($cat_list as $cat_id=>$category) {
			foreach ($category['forums'] as $forum_id=>$cur_forum) {
				$forum = & $cat_list[$cat_id]['forums'][$forum_id];

				if ($forum['num_topics'] > 0) continue;

				// it's possible we skipped this forum because it has no topics

				if (count($forum['subforums']) > 0) {
					list($num_topics,$num_posts) = $forum_model->loadSubforumsCounters($forum_id);
					$forum['num_topics'] += $num_topics;
					$forum['num_posts'] += $num_posts;
				}

			}
		}*/

		$this->view->assign('categories',$cat_list);
	}

	function setview()
	{
		$view = Agora::getVar('view');
		if ($view === 'topic') {
			Agora::setSessionVar('view','topic');
		} elseif ($view === 'forum') {
			Agora::setSessionVar('view','forum');
		} else {
			Agora::show404();
		}

        if (isset($_SERVER['HTTP_REFERER'])) {
			Agora::redirect($_SERVER['HTTP_REFERER']);
        } else {
        	Agora::redirect(Agora::makeURL(
				array(
					'task'	=>'index'
					))
				);
	    }
	}

	function _default()
	{
		$view = Agora::getSessionVar('view','forum');
		if ($view === 'topic') {
			$this->_topicView();
			$this->view->template = 'index_topics';
		} else {
			$this->_forumView();
			$this->view->template = 'index_forums';
		}
		if ($this->agora_user['is_superadmin']) {
			$this->view->assign('post_poll',1);
			$this->view->assign('post_topic',1);
		} else {
			if ($this->agora_user['is_guest']) {
				$banned = false;
			} else {
				$ban_model = & Model::getInstance('BanModel');
				$banned = $ban_model->isBanned($this->agora_user['username']);
			}
			$post_poll = $this->access_model->getAllowedForums($this->agora_user['id'],'post_poll');
			$post_topic = $this->access_model->getAllowedForums($this->agora_user['id'],'post_topic');
			$this->view->assign('post_poll',(count($post_poll) > 0) && (!$banned));
			$this->view->assign('post_topic',(count($post_topic) > 0) && (!$banned));
		}
	}
	
	function mark_read()
	{
		$topic_model = & Model::getInstance('TopicModel');
		$topic_model->markAllRead($this->agora_user['id'],  $this->agora_config['o_timeout_visit'] * 86400);
		Agora::redirect(Agora::getRefferer());
	}
}

?>
